package com.sali.asyncollection.service;



import com.sali.asyncollection.model.BaseRspDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @description:
 * @author: zhang hang
 * @date: 2023/3/15 16:59.
 * @version: 1.0
 */
public class ExecuteTaskService {

    /**
     * description: 并行调用模板
     *
     * @param taskList 待执行的任务列表
     * @param timeOut  CompletionService的poll方法获取时的超时时间
     * @param executor 线程池
     * @return:
     * @author: zhang hang
     * @date:
     **/
    public static List<BaseRspDTO<Object>> executeTask(List<Callable<BaseRspDTO<Object>>> taskList, long timeOut, ExecutorService executor) {

        List<BaseRspDTO<Object>> resultList = new ArrayList<>();
        //校验参数
        if (taskList == null || taskList.size() == 0) {
            return resultList;
        }
        if (executor == null) {
            return resultList;
        }
        if (timeOut <= 0) {
            return resultList;
        }

        //提交任务
        CompletionService<BaseRspDTO<Object>> baseDTOCompletionService = new ExecutorCompletionService<BaseRspDTO<Object>>(executor);
        for (Callable<BaseRspDTO<Object>> task : taskList) {
            baseDTOCompletionService.submit(task);
        }

        try {
            //遍历获取结果
            for (int i = 0; i < taskList.size(); i++) {
                Future<BaseRspDTO<Object>> baseRspDTOFuture = baseDTOCompletionService.poll(timeOut, TimeUnit.SECONDS);
                resultList.add(baseRspDTOFuture.get());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return resultList;
    }

}
